
#include "bjam.h"

#include "../filesystem_monitor.h"
#include "../utils.h"

#include <stdio.h>
#include <string.h>
#include <unistd.h>

void bb_bjam_builder_init(struct bb_bjam_builder* bdr, struct bb_view* view)
{
    bb_system_command_init(&(bdr->clear_screen_command), "clear");
    //bb_system_command_init(&(bdr->incremental_build_command), "bjam -j4 -q gtest 2>&1");
    bb_system_command_init(&(bdr->incremental_build_command), "./build.sh 2>&1");
    bdr->action_counter = 0;
    bdr->view = view;
}

void bb_bjam_builder_uninit(struct bb_bjam_builder* bdr)
{
    bb_system_command_uninit(&(bdr->incremental_build_command));
}

void bb_bjam_builder_on_filesystem_change(
    struct bb_bjam_builder* bdr, struct bb_filesystem_change const* change)
{
    (void)change;
    char const* line; size_t len;
    struct timeval before, after;
    char buffer[256];

    // Clear screen
    bb_system_command_start(&(bdr->clear_screen_command));
    while (bb_system_command_get_output_line(&(bdr->clear_screen_command), &line, &len)) ;

    // Incremental build
    ++bdr->action_counter;
    bb_current_time(&before);
    bb_announce_event(&before, bdr->action_counter, "performing incremental bjam build");
    bb_system_command_start(&(bdr->incremental_build_command));
    while (bb_system_command_get_output_line(&(bdr->incremental_build_command), &line, &len))
    {
        bb_view_on_build_output(bdr->view, line);
        /*char const* error = strstr(line, "error:");
        if (error)
        {
            int const prefix_len = (int)(error - line);
            fprintf(stdout, "%.*s\t\033[1;31m%*s\033[1;37m\n", prefix_len, line, (int)(len - prefix_len), error);
        }
        else
            fprintf(stdout, "%*s\n", (int)len, line);*/
    }
   
    //sleep(3);
    bb_current_time(&after);
    double const elapsed_seconds = 
        (after.tv_sec - before.tv_sec) + (after.tv_usec - before.tv_usec) / 1000000.0;
    sprintf(buffer, "incremental bjam build complete! (%.3f seconds)", elapsed_seconds);
    bb_announce_event(&after, bdr->action_counter, buffer);
    fflush(stdout);
}

